import EditList from '@/pages/Profile/Edit/EditList'
import {
  getUserProfile,
  updatePhoto,
  updateUserProfile,
} from '@/store/actions/profile'

import { useInitialState } from '@/utils/hooks'
import {
  Button,
  List,
  DatePicker,
  NavBar,
  Popup,
  Toast,
  Dialog,
} from 'antd-mobile'
import classNames from 'classnames'
import { useRef, useState } from 'react'
import { useDispatch } from 'react-redux'
import EditInput from './EditInput'

import styles from './index.module.scss'
import dayjs from 'dayjs'
import { logout } from '@/store/actions/login'
import { useHistory } from 'react-router-dom'

const Item = List.Item

type ShowInputType = {
  visible: boolean
  type: '' | 'name' | 'intro'
}

type ShowListType = {
  visible: boolean
  type: '' | 'photo' | 'gender'
}

const ProfileEdit = () => {
  const { userProfile } = useInitialState(getUserProfile, 'profile')

  //简介 昵称
  const [showInput, setShowInput] = useState<ShowInputType>({
    visible: false,
    type: '',
  })

  const dispatch = useDispatch()

  //关闭弹层
  const closeShowInput = () => {
    setShowInput({
      visible: false,
      type: '',
    })
  }
  //修改更新
  const onUpdate = async (key: string, value: string) => {
    // console.log(key, value)
    if (key === 'photo') {
      //需要修改头像
      fileRef.current!.click()
      return
    }
    await dispatch(updateUserProfile(key, value))
    Toast.show('修改成功')
    closeShowInput()
    closeShowList()
  }
  //----------性别 头像-------------
  const [showList, setShowList] = useState<ShowListType>({
    visible: false,
    type: '',
  })
  const closeShowList = () => {
    setShowList({
      visible: false,
      type: '',
    })
  }

  //文件上传
  const fileRef = useRef<HTMLInputElement>(null)

  //修改头像
  const onChangePhoto = async (e: React.ChangeEvent<HTMLInputElement>) => {
    console.log(e.target.files?.[0])

    const file = e.target.files?.[0]
    if (!file) return
    //异步文件上传=》formDate
    //1.创建formDate对象
    const fd = new FormData()
    //2.往这个formDate对象中，追加需要提交的数据 或 文件对象
    fd.append('photo', file)
    await dispatch(updatePhoto(fd))
    Toast.show('修改头像成功')
    closeShowList()
  }

  //----生日-------------
  const [showBirthday, setShowBirthday] = useState(false)

  const onShowBirthday = () => {
    setShowBirthday(true)
  }

  const closeShowBirthday = () => {
    setShowBirthday(false)
  }
  //-----退出----
  const history = useHistory()
  const clickLogout = () => {
    Dialog.show({
      title: '温馨提示',
      content: '你确定要退出吗？',
      closeOnAction: true,
      actions: [
        [
          { key: 'cancel', text: '取消', style: { color: 'blue' } },
          {
            key: 'confirm',
            text: '确定',

            onClick: () => {
              //1.清除token
              dispatch(logout())
              //2.跳转到登录
              history.push('/login')
              //3.提示
              Toast.show('退出成功')
            },
          },
        ],
      ],
    })
  }

  return (
    <div className={styles.root}>
      <div className="content">
        {/* 标题 */}
        <NavBar
          onBack={() => history.go(-1)}
          style={{
            '--border-bottom': '1px solid #F0F0F0',
          }}
        >
          个人信息
        </NavBar>

        <div className="wrapper">
          {/* 文件上传框 */}
          <input type="file" hidden ref={fileRef} onChange={onChangePhoto} />
          {/* 列表 */}
          <List className="profile-list">
            {/* 列表项 */}
            <Item
              extra={
                <span className="avatar-wrapper">
                  <img width={24} height={24} src={userProfile.photo} alt="" />
                </span>
              }
              arrow
              onClick={() =>
                setShowList({
                  visible: true,
                  type: 'photo',
                })
              }
            >
              头像
            </Item>
            <Item
              arrow
              extra={userProfile.name}
              onClick={() => {
                setShowInput({ visible: true, type: 'name' })
              }}
            >
              昵称
            </Item>
            <Item
              arrow
              extra={
                <span
                  className={classNames(
                    'intro',
                    userProfile.intro ? 'normal' : ''
                  )}
                >
                  {userProfile.intro || '未填写'}
                </span>
              }
              onClick={() =>
                setShowInput({
                  visible: true,
                  type: 'intro',
                })
              }
            >
              简介
            </Item>
          </List>

          <List className="profile-list">
            <Item
              arrow
              extra={userProfile.gender === 0 ? '男' : '女'}
              onClick={() =>
                setShowList({
                  visible: true,
                  type: 'gender',
                })
              }
            >
              性别
            </Item>
            <Item arrow extra={userProfile.birthday} onClick={onShowBirthday}>
              生日
            </Item>
          </List>

          <DatePicker
            visible={showBirthday}
            onCancel={closeShowBirthday}
            value={new Date(userProfile.birthday)}
            title="选择年月日"
            min={new Date(1900, 0, 1, 0, 0, 0)}
            max={new Date()}
            onConfirm={(value) => {
              onUpdate('birthday', dayjs(value).format('YYYY-MM-DD'))
              setShowBirthday(false)
            }}
          />
        </div>

        <div className="logout">
          <Button className="btn" onClick={clickLogout}>
            退出登录
          </Button>
        </div>
      </div>

      {/* 准备右侧飞出的弹层  简介和昵称*/}
      <Popup destroyOnClose visible={showInput.visible} position="right">
        {/* <div style={{ width: '100vw' }}>我是内容</div> */}
        <EditInput
          closeShowInput={closeShowInput}
          type={showInput.type}
          onUpdate={onUpdate}
        ></EditInput>
      </Popup>

      {/* 准备底部的弹层 修改性别和头像的弹层 */}
      <Popup
        visible={showList.visible}
        destroyOnClose
        position="bottom"
        onMaskClick={closeShowList}
      >
        <EditList
          type={showList.type}
          closeShowList={closeShowList}
          onUpdate={onUpdate}
        ></EditList>
      </Popup>
    </div>
  )
}

export default ProfileEdit
